<template>
	<el-link type="primary" :underline="false" @click="getAVerificationCode">
		{{ captchaText }}
	</el-link>
</template>
<script setup>
import {
	getSignUpGetPhoneValidCodeApi,
	getPhoneValidCodeApi,
	findPasswordGetPhoneValidCodeApi,
} from "@/api";
const props = defineProps({
	// 手机号
	phone: {
		type: String,
		default: "",
	},
	// 类型 ''
	type: {
		type: String,
		default: "",
	},
});
const emit = defineEmits(["getCode"]);

// 验证码文本
const captchaText = ref("获取验证码");
// 验证码状态
const captchaStatus = ref(true);
// 定时器
let timer = null;
// 获取验证码
const getAVerificationCode = async () => {
	if (captchaStatus.value) {
		if (!props.phone || props.phone === "") {
			return feedback.toast("请先输入手机号");
		}
		if (props.type === "register") {
			var { data, code } = await getSignUpGetPhoneValidCodeApi({
				phone: props.phone,
			});
		} else if (props.type === "login") {
			var { data, code } = await getPhoneValidCodeApi({
				phone: props.phone,
			});
		} else if (props.type === "reset") {
			var { data, code } = await findPasswordGetPhoneValidCodeApi({
				phone: props.phone,
			});
		}

		if (code == 200) {
			let time = 60;
			captchaText.value = "已发送 (" + time + "秒)";
			emit("getCode", data);
			timer = setInterval(() => {
				time--;
				captchaText.value = "已发送 (" + time + "秒)";
				captchaStatus.value = false;
				if (time <= 0) {
					clearInterval(timer);
					captchaText.value = "重新获取";
					captchaStatus.value = true;
				}
			}, 1000);
		}
	}
};
</script>
<style lang="scss" scoped></style>
